import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
import { UserService } from '@global/shared/user.service';
import { KeycloakService } from 'keycloak-iop/keycloak.service';
import { FcsStatusService } from '../service/fcs-status.service';
import { NavHeaderService } from '@global/layout/default/nav-header/nav-header.service';
import { CookiesService } from 'ng-zorro-iop/cookie/cookies';
import { Environment } from "environments/environment";
import { HttpClient } from "@angular/common/http";
import { async } from '@angular/core/testing';

@Injectable()
export class FcsServiceStateGuard implements CanActivate, CanActivateChild {
  static fcsServiceIsOpened = {}; // 判断fcs服务是否开通
  static fcsServiceSuspend = true; // 判断fcs服务是否欠费暂停

  constructor(
    private router: Router,
    private http: HttpClient,
    private userService: UserService,
    private keycloakService: KeycloakService,
    private fcsStatusService: FcsStatusService,
    private navHeaderService: NavHeaderService,
    private cookieService: CookiesService
  ) {
  }


  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    // FcsServiceStateGuard.fcsServiceIsOpened = false;


    let region  =  this.cookieService.getCookie('region');

    if (!FcsServiceStateGuard.fcsServiceIsOpened[region]) {

      let userId = this.keycloakService.getParentAccount();
      // console.log(userId)
      let res = await this.fcsStatusService.checkFCSServiceState(userId);
      let orderLists = res.result.orderList;  //开通的订单
      let orderIds = [];

      let regionLists = [];

      for(let i =0 ;i<orderLists.length;i++){
        orderIds.push(orderLists[i].orderId);  //开通的id数组
          let orders =  await this.fcsStatusService.checkFCSOrder(orderLists[i].orderId);
          regionLists.push(orders['result']['productList'][0]['region']);
      }
      if(!regionLists.includes(region)){//开通账号region的数组没有当前的region，则去开通
        this.router.navigate(['/fcs-not-opened']);
      }else{
        FcsServiceStateGuard.fcsServiceIsOpened[region] =true;
      }



      if (FcsServiceStateGuard.fcsServiceIsOpened[region] && FcsServiceStateGuard.fcsServiceSuspend) {
        let fcsSus = await this.fcsStatusService.checkFcsSuspendStatus();
        FcsServiceStateGuard.fcsServiceSuspend = !fcsSus || fcsSus.status !== 'normal';
        if (FcsServiceStateGuard.fcsServiceSuspend) {
          this.router.navigate(['/fcs-suspended']);
        }
      }
    }
    return (FcsServiceStateGuard.fcsServiceIsOpened[region] && !FcsServiceStateGuard.fcsServiceSuspend);
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    return this.canActivate(route, state);
  }

}
